package cn.wx.scholar.tool.jwt;

import cn.wx.common.persistence.exception.MyException;
//import cn.wx.common.persistence.redisson.RS;
import cn.wx.common.persistence.web.ResponseCode;
import cn.wx.common.persistence.web.ResponseData;
import com.alibaba.fastjson.JSON;

//import org.redisson.api.RMapCache;
//import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//import java.util.Map;
//import java.util.concurrent.TimeUnit;

/**
 * jwt拦截器
 */
public class JwtAuthFilter {

	Logger logger = LoggerFactory.getLogger(JwtAuthFilter.class);
	
	//public static final long C_EXPIRE_TIME = 5 * 60 * 1000;
	
	/*@Autowired
	private RedissonClient redissonClient;*/

	public Boolean filterInternal(HttpServletResponse response, String token,Boolean credis) {
		
		try {

			logger.info("request-token : " + token);
			
			/**
			 * 先验证token是否合法
			 */
			Long pId  = JwtUtil.validateToken(token);
			
			if(pId == null) {
				throw new MyException(ResponseCode.JWT_CHECK_ERROR);
			}

			/*if(credis) {
				RMapCache<Long,String> tokens = redissonClient.getMapCache(RS.REDIS_GENETOKEN);
				if(!tokens.containsKey(pId)) {
					throw new MyException(ResponseCode.JWT_CHECK_ERROR);
				}
				tokens.put(pId, "1", 1, TimeUnit.HOURS, 0, TimeUnit.HOURS);
			}*/
			
			return true;
			
		} catch (Exception e) {
			logger.info("request-token-exception : " + e.getMessage());
			response.setContentType("application/json;charset=utf-8");
			response.setStatus(200);
			response.setCharacterEncoding("utf-8");
			try {
				response.getWriter().write(JSON.toJSONString(ResponseData.ERROR("10001","token认证错误！",e.getMessage())));
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
			return false;
		}
	}

	
}